const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');

const User = require('../src/models/User');

const passport = require('passport');

passport.serializeUser((user, done) => {
    done(null, user.id)
});
passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
        done(err, user)
    })
})

passport.use(new LocalStrategy(
    {usernameField: 'email'},
    async (email, password, done) => {
        let user = await User.findOne({email})
        if(!user) return done(false, {message: '没有这个用户！'})

        bcrypt.compare(password, user.password, (err, isMatch) => {
            if(err) throw err;
            if(isMatch) {
                return done(user);
            }else{
                return done(false, {message: '密码错误！'})
            }
        })
    }
));

module.exports = passport
